'''
Description: IP处理工具模块
Author: HowsenFisher
Date: 2021-04-03 10:57:59
LastEditTime: 2021-04-11 01:14:38
LastEditors: liutq
Reference: 
'''
import re
import socket
import netifaces

'''
@description: 生成广播地址函数
@param  {*}
@return {*}
@param {*} ip：IP地址
@param {*} mask：子网掩码
'''
def generateBroadcastByIPAndMask(ip,mask):
    # 以"."分解IP
    ipList = [int(i) for i in ip.split(".")]
    # 以"."分解Mask
    maskList = mask.split(".")
    # 十进制转2进制
    res = "".join([str(bin(int(i)))[2:].rjust(8,"0") for i in maskList])
    # 取反
    res = "".join([str((int(i)+1)%2) for i in res])
    # 二进制8位为一组
    res = re.findall(r'.{8}',res)
    # 2进制转回十进制
    res = [int("0b"+i,2) for i in res]
    # 做或操作
    res = [str(i|j) for i,j in zip(ipList,res)]
    # 拼接或之后的IP，即为广播IP
    res = ".".join(res)
    return res

'''
@description: 获取本机IP函数
@param  {*}
@return {*}
'''
def GetIP():
    #获取计算机名称
    hostname=socket.gethostname()
    #获取本机IP
    ip=socket.gethostbyname(hostname)
    return ip

'''TODO
@description: 获取本机子网掩码函数
@param  {*}
@return {*}
'''
def GetMask():
    res=[]
    for i in netifaces.interfaces():
        res.append(netifaces.ifaddresses(i)[netifaces.AF_INET][0]['netmask'])
    return res

if __name__ == "__main__":
    res = GetMask()
    print(res)
